package com.halachawiki.server.data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

// Creates an 'integer' Key map
public class SessionKeyMap {

	static int latestKey = 0;
	
	private static Map<Integer,Object> getMap(HttpServletRequest request) { 
		HttpSession session = request.getSession();
		Map<Integer, Object> map = (Map<Integer, Object>)  session.getAttribute("keyMap");
		if (map == null) {
			synchronized(SessionKeyMap.class) {
				map = (Map<Integer, Object>)  session.getAttribute("keyMap");
				if (map != null) return map;
				map = new HashMap<Integer, Object>();
				session.setAttribute("keyMap", map);
			}
		}
		return map;
	}
	
	public static int getHandle(HttpServletRequest request, Serializable object) { 
		Map<Integer, Object> map = getMap(request);
		synchronized (map) {
			int handle = latestKey++;
			while (map.containsKey(handle)) {
				handle++;
			}
			map.put(handle, object);
			return handle;
		}
	}
	
	public static Object getObj(HttpServletRequest request, int handle) { 
		Map<Integer, Object> map = getMap(request);
		synchronized (map) {
			return getMap(request).get(handle);
		}
	}
	
	public static void deleteHandle(HttpServletRequest request, int handle) { 
		Map<Integer, Object> map = getMap(request);
		synchronized (map) {
			map.remove(handle);
		}
	}
	
}
